package org.example.springmvc1;


import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.*;

/**
 * 获取 cookie / session
 */
@RestController
@RequestMapping("/HeadController")
public class HeaderController {
    @RequestMapping("/getCookie1")
    //先需要获取请求
    public String getCookie1(HttpServletRequest request){
        Cookie[] cookies = request.getCookies();
        //然后根据 cookie
        if(cookies != null){
            for(Cookie cookie : cookies){
                System.out.println(cookie.getName()+":"+cookie.getValue());
            }
        }
        return "获取 cookie 成功";
    }
    //通过注解的方式获取 cookie ,在浏览器中的 cookie 中直接自定义添加 cookie
    @RequestMapping("/getCookie2")
    public String getCookie2(@CookieValue("name") String name){
        return "cookie: " + name;
    }

    //session 与 cookies 不同, cookies 是可以在浏览器中手动设置的, 但是 session 需要通过方法来设置
    //先设置 session, session 同样通过 HttpServletRequest 来设置
    @RequestMapping("/setSession")
    public String setSession(HttpServletRequest request){
        //session 通过 HttpSession 来接收
        HttpSession session = request.getSession();
        //通过 session.setAttribute 来设置 session, 前面的参数为字段,后面的参数为参数的值
        if(session != null) {
            session.setAttribute("name", "java");
        }
        return "设置 session 成功";
    }

    //获取 session 的值: 通过 HttpServletRequest 获取请求来获取 session
    @RequestMapping("/getSession1")
    public String getSession1(HttpServletRequest request){
        HttpSession session = request.getSession();
        if(session == null){
            return "没有获取到 session";
        }
        String name =  (String)session.getAttribute("name");
        System.out.println(session.getAttribute("name"));
        return "获取到了 session : name : " + name;
    }

    //获取 session 的值, 直接通过 HttpSession 获取瑟斯送到值
    @RequestMapping("/getSession2")
    public String Session2(HttpSession session){
        String name = (String) session.getAttribute("name");
        System.out.println(session.getAttribute("name"));
        return "获取到了 session, name: " + name;
    }

    //直接通过 @SessionAttribute 直接获取 session
    @RequestMapping("/getSession3")
    //实际上 @SessionAttribute 注解有两个参数 value 和 required
    //其中 value 是 Session 名, required 为 boolean 类型,为 true 时如果 Session 不存在的时候要创建 session
    public String getSession3(@SessionAttribute("name") String name){
        return "获取到了 session, name: " + name;
    }

    //获取 Header, 同样的 Header 也是通过 HttpServletRequest 获取
    @RequestMapping("/getHeader1")
    public String getHeader1(HttpServletRequest request){
            String name = request.getHeader("User-Agent");//这个参数是 http 协议报头中的参数
        return "获取到了 Header, name: " + name;
    }

    @RequestMapping("/getHeader2")
    public String getHeader2(@RequestHeader("User-Agent") String name){
        return "获取到了 Header, name: " + name;
    }
}
